<style scoped lang="scss">
.home {
  transition: all 1s ease-in-out;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 90vh;
  width: 100%;


  .dialog {
    width: 70%;
    height: 85vh;
    border-radius: 20px;
    box-shadow: 3px 3px 3px rgba(0, 0, 0, .3);
    //background-color: #1ab394;
    //margin-top: 200px;
    //margin-left: 700px;
    position: relative;


    .header {
      transition: all 1s ease-in-out;
      background-color: black;
      height: 4vh;
      line-height: 4vh;
      text-align: left;

      border-radius: 20px 20px 0 0;
    }

    .body {
      display: flex;
      height: 81vh;
      width: 100%;
      border-radius: 0 0 20px 20px;

      .left {
        transition: all 1s ease-in-out;
        box-sizing: border-box;
        border-right: 4px solid #2f2f2f;
        flex: 1;
        height: 100%;
        width: 25%;
        background-color: #242424;
        border-radius: 0 0 0 20px;

        .left-header {
          box-sizing: border-box;
          margin-left: 2%;
          width: 96%;
          height: 70%;
          border-bottom: 4px solid #2f2f2f;

          .chatList {
            height: 83%;
            width: 90%;
            margin-left: 5%;
            //border: 1px solid silver;
            overflow-y: scroll;
            text-align: left;
            margin-top: 30px;

            .chatItem {
              margin-top: 10px;
              cursor: pointer;
              font-size: 18px;
              height: 40px;
              line-height: 40px;
              margin-left: 10px;
              border-bottom: 1px solid #2f2f2f;

              &:hover {
                color: #c596f8;
                border-bottom: 1px dashed #c596f8;
                transition: all 1s ease-in-out;
              }
            }
          }

          .new {
            cursor: pointer;

            width: 90%;
            height: 30px;
            line-height: 30px;
            margin-top: 20px;
            border-radius: 15px;
            margin-left: 5%;
            text-align: center;
            border: 1px solid #b361d2;
          }
        }

        .left-footer {
          transition: all 1s ease-in-out;
          width: 90%;
          margin-left: 5%;
          margin-top: 20px;

          text-align: center;

          .language {
            transition: all 1s ease-in-out;
            font-size: 20px;
            height: 40px;
            line-height: 40px;
            cursor: pointer;
            margin-top: 8%;

            &:hover {
              font-size: 22px;
              color: aquamarine;
              //border-bottom: 1px solid rgba(255, 255, 255, .5);
              //background-color: rgba(255, 255, 255, .3);
              transition: all 0.5s ease-in-out;
            }
            //border: 1px solid silver;
          }
        }
      }

      .right {
        position: relative;
        height: 100%;
        width: 75%;
        border-radius: 0 0 20px 0;
        background-color: #121212;

        .demo {
          transition: all 1s ease-in-out;
          display: flex;
          justify-content: center;
          align-items: center;
          height: 80%;
          width: 100%;
          background-color: #121212;
        }

        .right-body {
          transition: all 1s ease-in-out;
          position: absolute;
          height: 80%;
          width: 100%;
          background-color: #121212;
          overflow-y: scroll;

          .from-us {
            //height: 90%;
            margin-top: 2%;
            margin-bottom: 3%;
            margin-right: 2%;
            width: 96%;
            text-align: right;
            position: relative;

            .time-box {
              width: 80%;
              position: absolute;
              right: 60px;
              height: 20px;
              color: #797979;
              //margin-right: 32px;
              margin-bottom: 3px;
            }

            .text-chat {
              margin-top: 20px;
              transition: all 1s ease-in-out;
              text-align: left;
              display: inline-block;
              padding: 10px;
              min-width: 0;
              max-width: 90%;
              min-height: 50px;
              line-height: 30px;
              border-radius: 10px;
              margin-right: 10px;
              background-color: #242424;
            }
          }

          .from-chatgpt {
            width: 96%;
            margin-top: 2%;
            margin-left: 2%;
            margin-bottom: 3%;


            .time-box {
              width: 80%;
              height: 20px;
              color: #797979;
              margin-left: 60px;
              margin-bottom: 3px;
            }


            .text-chat {
              transition: all 1s ease-in-out;
              word-break: break-all;
              display: inline-block;
              padding: 10px;
              padding-left: 20px;
              min-width: 0;
              max-width: 90%;
              min-height: 50px;
              line-height: 30px;
              border-radius: 10px;
              margin-left: 10px;
              background-color: #242424;
            }
          }
        }

        .right-footer {
          transition: all 1s ease-in-out;
          text-align: center;
          position: absolute;
          bottom: 0;
          height: 20%;
          width: 100%;
          border-radius: 0 0 20px 0;
          background-color: #242424;

          .ask {
            width: 100%;

            .text {
              display: inline-block;
              margin-top: 5%;
              width: 60%;
              margin-left: 5%;
              margin-right: 3%;

            }

            .ask-button {

              font-weight: 500;
              font-size: 16px;
            }
          }
        }
      }
    }

  }

  .dialog-mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5); /* 半透明黑色 */
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 500;
  }

  .dialog.myDialog-enter {
    width: 0;
    height: 0;
  }

  .dialog.myDialog-enter-active {
    transition: 0.5s all ease-in-out;
    overflow: hidden;
  }

  .dialog.myDialog-enter-to {
    width: 70%;
    height: 85vh;
  }

  .dialog.myDialog-leave {
    width: 70%;
    height: 85vh;
  }

  .dialog.myDialog-leave-active {
    transition: 0.5s all ease-in-out;
    overflow: hidden;
  }

  .dialog.myDialog-leave-to {
    width: 0;
    height: 0;
  }
}
</style>

<template>
  <div class="chatgpt home" :style="{color : fontColor}">

<!--    <div v-show="dialogVisible" class="dialog-mask"></div>-->
    <transition name="myDialog">
      <div v-show="dialogVisible" class="dialog">
        <div class="header" :style="{backgroundColor : tabColor}">
          <span style="margin-left: 10px">
            <svg-icon icon-class="chatgpt"/>
            ChatGPT</span>
        </div>
        <div class="body">
          <div class="left" :style="{backgroundColor : sideColor, borderRightColor : bColor}">
            <!-- 左上new chat-->
            <div class="left-header" :style="{borderBottomColor : bColor}">
              <div class="new" @click="newChat">
                <span>
                  <svg-icon style="margin-right: 10px" icon-class="plus"/>
                  <span v-show="language === 'english'">
                    New Chat
                  </span>

                  <span v-show="language === 'chinese'">
                    新建对话
                  </span>
                </span>
              </div>

              <div class="chatList">
<!--                <div class="chatItem" v-for="(item, index) in ChatList" :key="index" @click="ChangeChat(item)" v-show="chatId === item" :style="{border : '1px dashed #c596f8', color : '#c596f8'}">-->
<!--                  New Chat {{ item }}-->
<!--                </div>-->
                <div class="chatItem" v-for="(item, index) in ChatList" :key="index" @click="ChangeChat(item)" >
                  Chat {{ item }}
                </div>
              </div>
            </div>

            <div class="left-footer">
              <div class="language">
                <span @click="lchange">
                  <svg-icon style="margin-right: 10px" icon-class="international"/>
                    <span v-show="language === 'english'">
                      Chinese Change
                    </span>

                  <span v-show="language === 'chinese'">
                    切换英文
                  </span>
                </span>
              </div>

              <div class="language">
                <span v-show="mode === 'moon'" @click="modeChangeSun">
                  <svg-icon style="margin-right: 10px" icon-class="Sun"/>
                  <span v-show="language === 'english'">
                    Daytime mode
                  </span>
                  <span v-show="language === 'chinese'">
                    日间模式
                  </span>
                </span>

                <span v-show="mode === 'sun'" @click="modeChangeMoon">
                  <svg-icon style="margin-right: 10px" icon-class="moon"/>
                  <span v-show="language === 'english'">
                    Night mode
                  </span>
                  <span v-show="language === 'chinese'">
                    夜间模式
                  </span>
                </span>
              </div>

              <div class="language">
                <span>
                  <svg-icon style="margin-right: 10px" icon-class="time"/>
                  {{ currentTime }}
                </span>
              </div>
            </div>
          </div>
          <div class="right">

            <div v-show="chatId !== ''" class="right-body" ref="scrollBox" @scroll="handleScroll" :style="{backgroundColor : bgColor}">

              <div v-for="(item, index) in dialogue" :key="index">
                <div class="from-us" v-show="index % 2 == 0">
                  <img :src=$store.getters.avatar style="height: 50px;width: 50px;border-radius: 25px;float: right;"/>
                  <div class="time-box">
                    {{ item.qusTime }}
                  </div>
                  <div class="text-chat" ref="box" :style="{backgroundColor : sideColor}">
                  <span>
                    {{ item.question }}
                  </span>
                  </div>
                </div>



                <div class="from-chatgpt" v-show="index % 2 == 1">
                  <svg-icon style="height: 50px;width: 50px;border-radius: 25px;float: left;" icon-class="chatgpt"/>
                  <div class="time-box">
                    {{ item.ansTime }}
                  </div>
                  <div class="text-chat" ref="box" :style="{backgroundColor : sideColor}">
<!--                    <span>-->
<!--                      {{ item.answer }}-->
<!--                    </span>-->
                    <VueMarkdown :source="item.answer"></VueMarkdown>
                  </div>
                </div>
              </div>

            </div>

            <div v-show="chatId === ''" class="demo" :style="{backgroundColor : bgColor}">
              <el-empty v-show="language === 'chinese'" description="打开或新建一个对话来提问吧~"></el-empty>
              <el-empty v-show="language === 'english'" description="Open or create a new Chat to ask questions~"></el-empty>
            </div>

            <div class="right-footer" :style="{backgroundColor : sideColor}">
              <div class="ask">
                <v-text-field
                  v-show="mode === 'moon'"
                  label="ChatGPT"
                  placeholder="请向我进行提问~"
                  class="text"
                  dark
                  @keyup.ctrl.enter="askText"
                  v-model="question"
                ></v-text-field>

                <v-text-field
                  v-show="mode === 'sun'"
                  label="ChatGPT"
                  placeholder="请向我进行提问~"
                  class="text"
                  light
                  @keyup.ctrl.enter="askText"
                  v-model="question"
                ></v-text-field>

                <v-btn
                class="ask-button"
                large
                color="#c391fb"
                @click="askText"

                >
                  <span v-show="language === 'english'">
                    Send
                  </span>
                  <span v-show="language === 'chinese'">
                    发送
                  </span>
                  <svg-icon style="margin-left: 10px;" icon-class="send"/>
                </v-btn>
              </div>
            </div>
          </div>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
import {getChatList, getDialogue, newChat} from "@/api/chatgpt";
import VueMarkdown from "vue-markdown";
import moment from 'moment';
import log from "@/views/monitor/job/log.vue";

export default {
  components: {
    VueMarkdown,
  },
  data() {
    return {
      fontColor : '#fff',
      tabColor : '#000',
      bgColor : '#121212',
      sideColor : '#242424',
      bColor : '#2f2f2f',
      language : 'english',
      userScrolled: false,
      show : false,
      dialogVisible : false,
      mode : 'moon',
      ans : '',
      idx : '',
      loading : true,
      currentTime: new Date().toLocaleString(),
      dialogue : [
        // {
        //   question : '',
        //   qusTime : '',
        //   answer : '',
        //   ansTime : ''
        // }
      ],
      question : '',
      ChatList : [],
      chatId : ''
    };
  },
  computed: {
    boxWidth() {
      return this.$refs.box.scrollWidth + 'px';
    },
    boxHeight() {
      return this.$refs.box.scrollHeight + 'px';
    },
  },
  watch: {
    textContent() {
      this.$nextTick(() => {
        this.boxWidth;
        this.boxHeight;
      });
    }
  },
  methods: {
    modeChangeSun() {
      this.mode = 'sun'
      this.fontColor = '#000'
      this.bgColor = '#fff'
      this.sideColor = '#f2f2f2'
      this.tabColor = '#e3e3e3'
      this.bColor = '#bcbcbc'
    },
    modeChangeMoon() {
      this.mode = 'moon'
      this.fontColor = '#fff'
      this.bgColor = '#000'
      this.sideColor = '#242424'
      this.tabColor = '#121212'
      this.bColor = '#2f2f2f'
    },
    lchange() {
      if (this.language === 'english')
        this.language = 'chinese'
      else
        this.language = 'english'
    },
    getDialog() {

        this.dialogue = []
        getDialogue(this.chatId).then(response => {
        console.log(response)
        let idx = 0;
        for (let i = 0; i < response.data.qus.length; i ++ ) {
          this.dialogue[idx ++ ] = response.data.qus[i]
          this.dialogue[idx ++ ] = response.data.ans[i]
        }

        this.idx = idx
        this.userScrolled = false
        // this.dialogue.push(
        //   {
        //     question : '',
        //     qusTime : '',
        //     answer : '',
        //     ansTime : ''
        //   }
        // )

        console.log(this.dialogue)
      })

    },
    updateTime() {
      this.currentTime = new Date().toLocaleString();
      setTimeout(() => {
        this.updateTime();
      }, 1000); // 更新间隔为1秒
    },
    openDialog() {
      this.dialogVisible = true;

      document.body.style.overflow = 'hidden';
    },
    closeDialog() {
      this.dialogVisible = false;


    },
    askText() {
      if (this.question !== '' && this.chatId !== '')
        this.sendMessage()
    },
    getChatList() {
      getChatList().then(response => {
        this.ChatList = response.data
      })
    },
    newChat() {
      newChat()
      this.getChatList()
    },
    ChangeChat(chatId) {
      this.chatId = chatId
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',

        background: 'rgba(0, 0, 0, 0.1)',
        target: document.querySelector('.right-body')
      });
      this.getDialog()
      loading.close()
      this.connectWebsocket()
    },
    scrollToBottom() {
      if (!this.userScrolled) {
        console.log("滑到底部")
        this.$nextTick(() => {
          const scrollBox = this.$refs.scrollBox;
          scrollBox.scrollTop = scrollBox.scrollHeight;
        });
        console.log("滑到底部2")
      }
    },
    handleScroll() {
      this.userScrolled = true;
    },
    sendMessage() {
      this.userScrolled = false
      if (this.dialogue[this.idx] === undefined) {
        this.dialogue.push(
          {
            question : '',
            qusTime : '',
            answer : '',
            ansTime : ''
          }
        )
      }
      if (this.question) {
        // 发送消息到WebSocket服务器
        let qusTime = this.currentTime

        this.websocket.send(
          JSON.stringify({
            question : this.question,
            qusTime : qusTime
          })
        );
        this.dialogue[this.idx].question = this.question
        this.dialogue[this.idx].qusTime = qusTime
        this.idx ++
        this.question = ''
      }
    },
    connectWebsocket() {
      this.websocket = new WebSocket('ws://127.0.0.1:1145/chatgpt/u' + this.$store.getters.id + 'c' + this.chatId);
      console.log("777")

      // 监听WebSocket连接打开事件
      this.websocket.onopen = () => {
        console.log('WebSocket connected');
      };

      // 监听WebSocket消息事件
      this.websocket.onmessage = (event) => {
        this.userScrolled = false
        console.log(this.idx)
        if (this.dialogue[this.idx] === undefined) {
          this.dialogue.push(
            {
              question : '',
              qusTime : '',
              answer : '',
              ansTime : ''
            }
          )
        }
        console.log(this.dialogue[this.idx].answer)

        let str = event.data

        if (!str.includes("ayiayibaba")) {
          this.dialogue[this.idx].answer += event.data
        } else {
          this.idx ++
          let time = str.replace("ayiayibaba", "")
          let ansTime = moment(time).format('YYYY/MM/DD HH:mm:ss')
          console.log(ansTime)
          this.dialogue[this.idx - 1].ansTime = ansTime
          console.log(this.dialogue[this.idx - 1].ansTime)
          console.log("new dia => " + this.dialogue)
        }

      };
    }
  },
  mounted() {
    this.openDialog()
    this.updateTime();
    this.getChatList()
    if (this.chatId !== '')
      this.getDialog()

  },

  updated() {
    this.scrollToBottom();
  },
  created() {
    console.log("666")
    // 连接WebSocket

  },
  destroyed() {
    this.closeDialog()
  },
  beforeRouteLeave(to, from, next) {
    console.log("666")
    // 关闭遮罩层的逻辑，可以根据实际需求进行调整
    this.closeDialog()
    next();
  }
};
</script>
